const req = require('requests.js')

Array.prototype.contains = function (obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

function album_save(album, callback) {
  var tmp_images = []
  album.datas.forEach(function(item) {
    var url = item.url
    if (url && url.indexOf('http://tmp') != -1) {
      // 本地图片, 添加进去
      tmp_images.push(url)
    }
  })
  if (album.cover && album.cover.url && album.cover.url.indexOf('http://tmp') != -1) {
    // 封面图为临时图片
    tmp_images.push(album.cover.url)
  }
  // 去重
  var local_images = []
  tmp_images.forEach(function(item) {
    if (local_images.contains(item) == -1) {
      local_images.push(item)
    }
  })
  // 上传图片
  req.updateAlbumImages({
    albumId: album.id,
    images: local_images,
    complate: function (net_imgs) { 
      var local_datas = album.datas

      net_imgs.forEach(function(net_img, index) {
        var url = net_img.url
        var tmp_path = local_images[index]
        // 替换内容图片
        album.datas.forEach(function(local_item) {
          if (local_item.url == tmp_path) {
            local_item.url = url
            local_item.source = net_img.source
          }
        })
        // 替换封面图
        if (album.cover.url == tmp_path) {
          album.cover.url = url
        }
      })

      callback(album)
    },
    progress: function (progress) { }
  })
}


module.exports = {
  album_save: album_save,
}